package com.l.im.mq;


import com.l.im.model.GroupMessageDTO;
import com.l.im.service.handler.MessageDispatcher;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.consumer.MessageListener;
import org.apache.rocketmq.client.apis.message.MessageView;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import com.alibaba.fastjson.JSON;
import com.l.im.common.api.ApiResponse;


/**
 * @program: LIM
 * @description: 单聊信息处理类
 * @author: Alex Wu
 * @createDate: 2025-04-15 14:25
 **/
@Slf4j
public class GroupMessageListener implements MessageListener {

    @Override
    public ConsumeResult consume(MessageView messageView) {
        String messageId = messageView.getMessageId().toString();
        ByteBuffer body = messageView.getBody();
        String bodyStr = StandardCharsets.UTF_8.decode(body).toString();
        log.info("Received group MQ message: id={}, body={}", messageId, bodyStr);

        GroupMessageDTO groupMessageDTO = JSON.parseObject(bodyStr, GroupMessageDTO.class);

        String[] userIdList = groupMessageDTO.getToUserIds().split(",");
        for (String toUserId : userIdList) {
            toUserId = toUserId.trim();
            MessageDispatcher.sendToUser(toUserId, ApiResponse.success(groupMessageDTO));
        }
        return ConsumeResult.SUCCESS;
    }
}
